package com.xuerhua.yxt.controller.sys;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.xuerhua.yxt.common.AdminUser;
import com.xuerhua.yxt.common.Constants;
import com.xuerhua.yxt.common.RspResult;
import com.xuerhua.yxt.common.enums.Status;
import com.xuerhua.yxt.controller.BaseController;
import com.xuerhua.yxt.model.SchoolCommentWeek;
import com.xuerhua.yxt.model.SysCommentTemplate;
import com.xuerhua.yxt.service.ISchoolCommentWeekService;
import com.xuerhua.yxt.service.ISysCommentTemplateService;
import com.xuerhua.yxt.utils.CellUtil;
import com.xuerhua.yxt.utils.DateUtil;

@RequestMapping("sys/file")
@Controller
public class FileController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(FileController.class);

	@Autowired
	private ISysCommentTemplateService sysCommentTemplateService;
	@Autowired
	private ISchoolCommentWeekService schoolCommentWeekService;
	
	@RequestMapping("commentTemplate/import")
	@ResponseBody Object commentTemplateImport(@RequestParam(value="files",required=false) MultipartFile buildInfo, String dictDataKey) {
		try {
			return saveCommentInfo(buildInfo, dictDataKey);
		} catch (Exception e) {
			logger.error("--commentTemplateImport, error={}", e);
		}
		return new RspResult(Status.TEMPLATE_ERROR);
	}
	
	@RequestMapping("weekTemplate/import")
	@ResponseBody Object weekTemplateImport(@RequestParam(value="files",required=false) MultipartFile buildInfo, Integer termId) {
		try {
			return saveWeekInfo(buildInfo, termId);
		} catch (Exception e) {
			logger.error("--weekTemplateImport, error={}", e);
		}
		return new RspResult(Status.TEMPLATE_ERROR);
	}
	
	public RspResult saveCommentInfo(MultipartFile buildInfo, String dictDataKey) throws Exception{
		AdminUser adminUser = getAdminUser();
    	// 创建一个FileInputStream 文件输入流
        InputStream inputStream = buildInfo.getInputStream();
    	// 创建对Excel工作簿文件的引用
        Workbook wookbook = null;	
        String filename = buildInfo.getOriginalFilename();
        String fileType = filename.substring(filename.lastIndexOf(".") + 1,
        		filename.length());
        if (fileType.equals("xls")) {
        	try{
        		wookbook = new HSSFWorkbook(inputStream);
        	}catch(Exception e){
        		wookbook = null;
           	 	wookbook = new XSSFWorkbook(inputStream);
        	}
        }else{
       	 	wookbook = new XSSFWorkbook(inputStream);
        }
        // 在Excel文档中，第一张工作表的缺省索引是0
        Sheet sheet = wookbook.getSheetAt(0);
        int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();// 获取总列数
        int rowNum=sheet.getPhysicalNumberOfRows();//获得总行数
        if(rowNum <= 1) {
        	return new RspResult(Status.TEMPLATE_DATA_NULL);
        }
        List<SysCommentTemplate> list = new ArrayList<>();
        // 遍历行 从第三行开始遍历
        for (int i = 1; i < rowNum; i++) {
        	// 读取左上端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {
            	SysCommentTemplate signInfo = new SysCommentTemplate();
            	signInfo.setDictDataKey(dictDataKey);
            	for(int j = 0; j < coloumNum; j ++) {
            		Cell cell = row.getCell((short)j);
            		if(cell != null) {
            			String val = CellUtil.getCellValue(cell);
            			if(j == 0) signInfo.setTemplateContent(val);
            		}
            	}
            	signInfo.setSchoolId(adminUser.getTeacherInfo().getSchoolId());
            	list.add(signInfo);
            }
        }
        sysCommentTemplateService.insertBatch(list);
        return new RspResult(Status.SUCCESS);
    }
	
	public RspResult saveWeekInfo(MultipartFile buildInfo, Integer termId) throws Exception{
		AdminUser user = (AdminUser) request.getSession().getAttribute(Constants.ADMIN_USER);
		// 创建一个FileInputStream 文件输入流
        InputStream inputStream = buildInfo.getInputStream();
    	// 创建对Excel工作簿文件的引用
        Workbook wookbook = null;
        String filename = buildInfo.getOriginalFilename();
        String fileType = filename.substring(filename.lastIndexOf(".") + 1,
        		filename.length());
        if (fileType.equals("xls")) {
        	try{
        		wookbook = new HSSFWorkbook(inputStream);
        	}catch(Exception e){
        		wookbook = null;
           	 	wookbook = new XSSFWorkbook(inputStream);
        	}
        }else{
       	 	wookbook = new XSSFWorkbook(inputStream);
        }
        // 在Excel文档中，第一张工作表的缺省索引是0
        Sheet sheet = wookbook.getSheetAt(0);
        int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();// 获取总列数
        int rowNum=sheet.getPhysicalNumberOfRows();//获得总行数
        if(rowNum <= 1) {
        	return new RspResult(Status.TEMPLATE_DATA_NULL);
        }
        List<SchoolCommentWeek> list = new ArrayList<>();
        // 遍历行 从第三行开始遍历
        for (int i = 1; i < rowNum; i++) {
        	// 读取左上端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            if (row != null) {
            	SchoolCommentWeek signInfo = new SchoolCommentWeek();
            	signInfo.setTermId(termId);
            	for(int j = 0; j < coloumNum; j ++) {
            		Cell cell = row.getCell((short)j);
            		if(cell != null) {
            			String val = CellUtil.getCellValue(cell);
            			if(j == 0) signInfo.setWeekNo(Integer.valueOf(val));
            			else if(j == 1) signInfo.setStartDate(DateUtil.dateToStr(DateUtil.strToDate(val, DateUtil.DEFAULT_DATE_FORMAT3),
            					DateUtil.DEFAULT_DATE_FORMAT3));
            			else if(j == 2) signInfo.setEndDate(DateUtil.dateToStr(DateUtil.strToDate(val, DateUtil.DEFAULT_DATE_FORMAT3),
            					DateUtil.DEFAULT_DATE_FORMAT3));
            		}
            	}
            	signInfo.setSchoolId(user.getTeacherInfo().getSchoolId());
            	list.add(signInfo);
            }
        }
        schoolCommentWeekService.insertBatch(list);
        return new RspResult(Status.SUCCESS);
    }
	
}